import { Badge, Button, Modal, Tooltip } from 'antd'
import { CloseSquareOutlined, MailOutlined } from '@ant-design/icons'

import { addAGCellTexty } from '@oBiz/components/addTexty'
import { SendTplEmailDrawer } from '../SendEmailDrawer'
import { popupSlot } from '../utils'
import { apiCncelNotice } from './apis'
import { TCellParams } from './interface'
import { useBoundStore } from './store'

export const Cell = (p: TCellParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'noticeStatus': {
      const { value, valueFormatted } = p as TCellParams<'noticeStatus'>
      if (value == null) return
      return (
        <Badge color={{ 0: 'blue', 1: 'green', 2: $CSS_VAR.statusDefault }[value]} text={valueFormatted || value} />
      )
    }
    case 'noticeId': {
      return <ActionCell {...(p as TCellParams<'noticeId'>)} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

function ActionCell({ value, data }: TCellParams<'noticeId'>) {
  const changeNoticeStatus = useBoundStore(v => v.changeNoticeStatus)
  if (value == null || !data) return
  const { noticeStatus } = data
  return (
    <>
      {noticeStatus === 0 && (
        <Tooltip title="发送通知邮件">
          <Button
            type="link"
            icon={<MailOutlined />}
            onClick={() => {
              if (value == null) return
              const modalUpdate = popupSlot.insert(
                <SendTplEmailDrawer
                  noticeId={data.noticeId}
                  destroy={() => modalUpdate(null)}
                  onSuccess={() => changeNoticeStatus(data.noticeId, 1)}
                />,
              )
            }}
          />
        </Tooltip>
      )}
      {noticeStatus === 0 && (
        <Tooltip title="取消">
          <Button
            type="link"
            danger
            icon={<CloseSquareOutlined />}
            onClick={() => {
              Modal.confirm({
                title: '确认要取消吗？',
                onOk: async () => {
                  await apiCncelNotice(data.noticeId)
                  changeNoticeStatus(data.noticeId, 2)
                },
              })
            }}
          />
        </Tooltip>
      )}
    </>
  )
}
